package main

import (
	"database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

//方案一使用指针方式实现零值存入数据库   目的是给数据库传入空值
//type Test struct {
//	ID           int64
//	Name         *string  `gorm:"default:'小王子'"`  // sql.NullString 实现了Scanner/Valuer接口
//	Age          int64
//}
//方案二 使用Scanner/Valuer接口方式实现零值存入数据库
type Test struct {
	ID   int64
	Name sql.NullString `gorm:"default:'小王子'"` // sql.NullString 实现了Scanner/Valuer接口
	Age  int64
}

func insertDB1() {
	db2, err := gorm.Open("mysql", "root:root@/blog?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	//var  t=Test{ Name: sql.NullString{"",true},Age: 15,}
	db2.AutoMigrate(&Test{}) //关联表
	//fmt.Println(db2.NewRecord(t)) // 主键为空返回`true`
	//db2.Create(&t)   // 创建user
	//fmt.Println(db2.NewRecord(t)) // 创建`user`后返回`false`
	//var test []Test
	//db2.First(&test)    //查找第一条数据
	//fmt.Println(test.Age,test.ID,test.Name)
	//  db2.Find(&test)    //查找数据库所有数据
	//for _,val:=range test{
	//	fmt.Println(val.ID,val.Name,val.Age)
	//}
	//条件查询
	//var testWhere Test
	// db2.Where("id=?",3).First(&testWhere)
	//fmt.Println(testWhere)
	//var testWhere1 []Test
	//db2.Where("id in (?)",[]int{2,3,4,5,6,7,8}).Find(&testWhere1)
	//for _,val:=range testWhere1{
	//		fmt.Println(val.ID,val.Name,val.Age)
	//	}
	//Struct & Map查询
	//	var user Test
	//	var users []Test
	//	db2.Where(&Test{Name: sql.NullString{"雷必东",true}, Age: 11}).First(&user)
	//	//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1;
	//	fmt.Println(user)
	//	// Map
	//	db2.Where(map[string]interface{}{"name": "雷必东", "age": 11}).First(&user)
	//	//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
	//fmt.Println(user)
	//	// 主键的切片
	//	db2.Where([]int64{2, 3, 4}).Find(&users)
	//	//// SELECT * FROM users WHERE id IN (20, 21, 22);
	//	fmt.Println(users)
	//db.Not("name", "jinzhu").First(&user)
	//// SELECT * FROM users WHERE name <> "jinzhu" LIMIT 1;
	//更新字段
	//var t3 Test
	//db2.Where("age=?",57).First(&t3)
	//t3.Age=58
	//t3.Name=sql.NullString{"sdfssds",false}
	////db2.Save(&t3)    //修改字段
	//db2.Model(&t3).Update("age","name")    //更新指定字段
	//db2.Where("id=?",3).Delete(&t3)   //删除指定字段 软删除
	// Unscoped 方法可以物理删除记录
	//db.Unscoped().Delete(&order)
	//使用原生sql
	var yuan []Test
	db2.Raw("select * from tests ").Scan(&yuan)
	fmt.Println(yuan)
	defer db2.Close()
}
func yuanshensql() {
	db2, err := gorm.Open("mysql", "root:root@/blog?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	db2.AutoMigrate(&Test{}) //关联表
	//查询
	//var yuan []Test
	//db2.Raw("select * from tests ").Scan(&yuan)
	//fmt.Println(yuan)
	//添加
	//db2.Exec("insert into tests(name,age) values(?,?)","你还",78)
	//更新
	//db2.Exec("update tests set age =1 where id =? ",7)
	//删除
	db2.Exec("delete from tests where id in(?)", []int{3, 4, 5})
	defer db2.Close()
}
func main() {
	//insertDB1()
	yuanshensql()
}
